#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <cassert>
#include <sys/epoll.h>
#include <sys/types.h>
#include <iostream>
#include "./locker/locker.h"
#include "./threadpool/threadpool.h"
#include "./http_conn/http_conn.h"
#define MAX_FD 65536
#define MAX_EVENT_NUMBER 10000
#define PORT 9100

extern int addfd(int epollfd, int fd, bool one_shot);
extern int removefd(int epollfd, int fd);

void addsig(int sig,void(handler)(int),bool restart=true)
{
    struct sigaction sa;
    memset(&sa, '\0', sizeof(sa));
    sa.sa_handler = handler;
    if(restart)
    {
        sa.sa_flags |= SA_RESTART;
    }
    sigfillset(&sa.sa_mask);
    assert(sigaction(sig, &sa, NULL) != -1);
}

void show_error(int connfd,const char* info)
{
    printf("%s", info);
    send(connfd, info, strlen(info), 0);
    close(connfd);
}

#define ERR_EXIT(m) \
do\
{\
    perror(m);\
    exit(EXIT_FAILURE);\
}\
while (0);\

void create_daemon(void)
{
    pid_t pid;
    pid = fork();
    if( pid == -1)
        ERR_EXIT("fork error");
    if(pid > 0 )
        exit(EXIT_SUCCESS);
    if(setsid() == -1)
        ERR_EXIT("SETSID ERROR");
    chdir("/");
    int i;
    for( i = 0; i < 3; ++i)
    {
        close(i);
        open("/dev/null", O_RDWR);
        dup(0);
        dup(0);
    }
    umask(0);
    return;
}
int main(int argc,char*argv[])
{
    //守护进程
   create_daemon();
    /*忽略SIGPIPE信号*/
    addsig(SIGPIPE, SIG_IGN);
    //需要修改的数据库信息,登录名,密码,库名
    string user = "root";
    string passwd = "zzc5201314";
    string databasename = "mycinema";
    http_conn *users = new http_conn[MAX_FD];
    assert(users);
    /*创建连接池*/
    connection_pool *connpool=connection_pool::GetInstance();
    connpool->init("localhost", user, passwd, databasename, 3306, 8, 0);
    //初始化数据库读取表
    users->initmysql_result(connpool);
    /*创建线程池*/
    threadpool<http_conn> *pool = NULL;
    try
    {
        pool = new threadpool<http_conn>;
    }
    catch(...)
    {
        return 1;
    }

    /*预先为每个可能的客户分配一个http_conn对象*/
    int user_count = 0;

    int listenfd = socket(PF_INET, SOCK_STREAM, 0);
    assert(listenfd >= 0);
    struct linger tmp = {1, 0};
    setsockopt(listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp));

    int ret = 0;
    struct sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = htonl(INADDR_ANY);
    address.sin_port = htons(PORT);

    ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address));
    assert(ret >= 0);

    ret = listen(listenfd, 5);
    assert(ret >= 0);

    epoll_event events[MAX_EVENT_NUMBER];
    int epollfd = epoll_create(5);
    addfd(epollfd, listenfd, false);
    http_conn::m_epollfd = epollfd;

    while(true)
    {
        int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1);
        if((number<0)&&errno!=EINTR)
            {
                printf("epoll failure\n");
                break;
            }
		printf("epoll ok\n");
            for (int i = 0; i < number;i++)
            {
                int sockfd = events[i].data.fd;
                if (sockfd == listenfd)
                {
                    struct sockaddr_in client_address;
                    socklen_t client_addrlength = sizeof(client_address);
                    int connfd = accept(listenfd, (struct sockaddr *)&client_address, &client_addrlength);
                    if (connfd < 0)
                    {
                        printf("errno is: %s\n", errno);
                        continue;
                    }
                    if(http_conn::m_user_count>=MAX_FD)
                    {
                        show_error(connfd, "Internal server busy");
                        continue;
                    }
                    users[connfd].init(connfd, client_address);
			printf("create a conn %d %s\n",connfd,&client_address);
                }
                else if (events[i].events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR))
                {
		printf("error to connect\n");
                    users[sockfd].close_conn();
                }
                else if (events[i].events & EPOLLIN)
                {
                    if(users[sockfd].read())
                    {
			printf("reading... %d\n",sockfd);
                        pool->append(users + sockfd);
                    }
                    else
                    {
			printf("nothing to read\n");
                        users[sockfd].close_conn();
                    }
                }
                else if(events[i].events&EPOLLOUT)
                {
                    if(!users[sockfd].write())
                    {
			printf("nothing to write\n");
                       users[sockfd].close_conn();
                    }
			printf("writting... %d\n",sockfd);
		}
                 else
                    {}
               
            }
    }
    close(epollfd);
    close(listenfd);
    delete [] users;
    delete pool;
    return 0;
}
